#pragma managed

#include "Database.h"
#include <io.h>

CDatabase::CDatabase()
{
	fname = NULL;
}

CDatabase::CDatabase(const TCHAR *file)
{
	Attach(file);
}

void CDatabase::Attach(const TCHAR *file)
{
	fname = new TCHAR[lstrlen(file) + 1];
	lstrcpy(fname, file);
	section.Set(fname, 0);
	if (!section.getFile())
		return;
	while (!section.Eos())
	{
		unsigned long pos;
		section.Read(pos);
		CFSstate *state = new CFSstate(section.getFile(), pos);
		shots.push_back(state);
	}
}

SYSTEMTIME CDatabase::getTime(size_t num)
{
	if (num >= shots.size())
	{
		SYSTEMTIME time;
		ZeroMemory(&time, sizeof(time));
		return time;
	}
	return shots[num]->getTime();
}

void CDatabase::MakeShot(const std::vector<_tstring> &list)
{
	SYSTEMTIME st;
	GetLocalTime(&st);
	unsigned long pos = filelength(fileno(section.getFile()));
	section.Write(pos);
	CFSstate *state = new CFSstate(section.getFile(), st);
	shots.push_back(state);
	size_t sz = list.size();
	
	for (size_t i = 0; i < sz; i++)
	{
		TCHAR *prepath = new TCHAR[list[i].length() + 1];
		lstrcpy(prepath, list[i].c_str());
		int pos;
		for (pos = lstrlen(prepath) - 1; pos > 0; pos--)
			if (prepath[pos] == '\\')
			{
				prepath[pos] = '\0';
				break;
			}
		if (pos < 0)
			prepath[0] = '\0';

		WIN32_FIND_DATA fd;
		if (list[i].length() > 1)
			if (list[i][list[i].length() - 1] == ':')
			{
				fd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
				fd.nFileSizeHigh = 0;
				fd.nFileSizeLow = 0;
				fd.ftLastAccessTime.dwHighDateTime = 0;
				fd.ftLastAccessTime.dwLowDateTime = 0;
				fd.ftCreationTime.dwHighDateTime = 0;
				fd.ftCreationTime.dwLowDateTime = 0;
				fd.ftLastWriteTime.dwLowDateTime = 0;
				lstrcpy(fd.cFileName, list[i].c_str());
				state->AddEntry(prepath, new CEntry(list[i].c_str(), fd, section.getFile(), 0, NULL));
				continue;
			}
		
		HANDLE fnd = FindFirstFile(list[i].c_str(), &fd);
		if (fnd != INVALID_HANDLE_VALUE)
		{
			state->AddEntry(prepath, new CEntry(list[i].c_str(), fd, section.getFile(), 0, NULL));
			FindClose(fnd);
		}
		delete [] prepath;
	}
}

void CDatabase::Clear()
{
	size_t sz = shots.size();
	for (size_t pos = 0; pos < sz; pos++)
		delete shots[pos];
	shots.clear();
	if (fname)
	{
		delete [] fname;
		fname = NULL;
	}

	section.Finish();
}

CDatabase::~CDatabase()
{
	Clear();
}
